package com.ruoyi.business.service.impl;

import org.springframework.stereotype.Service;
import com.ruoyi.business.domain.PaymentOrder;
import com.ruoyi.business.domain.PaymentResult;
import com.ruoyi.business.mapper.PaymentMapper;
import com.ruoyi.business.service.IPaymentService;
import com.github.wxpay.sdk.WXPay;
import com.github.wxpay.sdk.WXPayUtil;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

/**
 * @author 22714
 */
@Service
public class PaymentServiceImpl implements IPaymentService {

    private  PaymentMapper paymentMapper;
    private  WXPay wxPay;

    @Override
    public String createPaymentOrder(PaymentOrder order) {
        // 插入支付订单记录到数据库
        paymentMapper.insertPaymentOrder(order);
        try {
            Map<String, String> data = new HashMap<>();
            data.put("body", order.getBody());
            data.put("out_trade_no", order.getOrderNo());
            data.put("total_fee", order.getTotalFee().multiply(new BigDecimal(100)).intValue() + "");
            data.put("spbill_create_ip", "127.0.0.1");
            data.put("notify_url", "your_notify_url");
            data.put("trade_type", "NATIVE");
            Map<String, String> result = wxPay.unifiedOrder(data);
            return result.get("code_url");
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    @Override
    public PaymentResult handlePaymentCallback(String callbackData) {
        try {
            Map<String, String> notifyMap = WXPayUtil.xmlToMap(callbackData);
            if (wxPay.isPayResultNotifySignatureValid(notifyMap)) {
                if ("SUCCESS".equals(notifyMap.get("result_code"))) {
                    paymentMapper.updatePaymentStatus(notifyMap.get("out_trade_no"), "已支付");
                    PaymentResult result = new PaymentResult();
                    result.setSuccess(true);
                    return result;
                }
            }
            PaymentResult result = new PaymentResult();
            result.setSuccess(false);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            PaymentResult result = new PaymentResult();
            result.setSuccess(false);
            return result;
        }
    }

    @Override
    public PaymentOrder selectPaymentOrderByOrderNo(String orderNo) {
        return paymentMapper.selectPaymentOrderByOrderNo(orderNo);
    }
}